#!/bin/bash
sig=''

# ps -ef |grep python | grep -v auto | grep -v 948 | awk '{print $2}' | xargs kill -9

help() {
	echo "Usage: dispatch [-h] [-s signal]"
	echo "Options:"
	echo "   -h      : this help"
	echo "   -s      : send signal to master process: start,stop,quit,restart" 
}

send_sig() {
    source ./dispatch_pid.sh
    case $sig in
        "start")
          if [ -d "/proc/$DISPATCH_MASTER_PID" ]; then
              echo "服务已启动"
          else
              echo "启动服务..."
              nohup python3 ./bootstrap.py &
          fi
	      ;;
        "stop")
	      echo "优雅停止服务...(kill -3 $DISPATCH_MASTER_PID)"
	      kill -3 $DISPATCH_MASTER_PID
	      ;;
        "restart")
	      echo "重启服务...(kill -1 $DISPATCH_MASTER_PID)"
	      kill -1 $DISPATCH_MASTER_PID
	      ;;
        "quit")
	      echo "停止服务...(kill -2 $DISPATCH_MASTER_PID)"
	      kill -2 $DISPATCH_MASTER_PID
	      ;;
        *)
          echo "未知操作"
          help
    esac

}


while getopts "s:h" opt; do
    case $opt in
        h)  # 显示帮助 无需参数
            help
            exit 1
            ;;
        s)  # 信号类别（-s 需要带参数）
            sig="$OPTARG"
            send_sig
            exit 1
            ;;
        \?) # 无效选项
            echo "错误：未知选项 -$OPTARG" >&2
            help
            exit 1
            ;;
        :)  # 选项缺少参数
            echo "错误：选项 -$OPTARG 需要参数" >&2
            help
            exit 1
            ;;
    esac
done

